package com.gusti.turnos.servlet.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.gusti.turnos.util.ServerUtil;

/**
 * 
 * @author gusti
 *
 */
public class AuthenticationFilter implements Filter {

	private FilterConfig filterConfig;

	public void init( FilterConfig filterConfig ) {
		this.filterConfig = filterConfig;
	}

	public void destroy() {
		this.filterConfig = null;
	}

	public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws ServletException, IOException {

		if ( filterConfig == null) {
			return;
		}

		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpSession session = httpRequest.getSession(false);
		HttpServletResponse httpResponse = (HttpServletResponse) response;

		if( session == null && httpRequest.getRequestedSessionId() != null && !httpRequest.isRequestedSessionIdValid() ) {
			httpResponse.setStatus( HttpServletResponse.SC_REQUEST_TIMEOUT );
			return;
		}

		if ( session == null || session.getAttribute( ServerUtil.CURRENT_USER ) == null ) {
//			httpResponse.addHeader("WWW-Authenticate", "BASIC realm=\"My Web Site\"");
			httpResponse.setStatus( HttpServletResponse.SC_UNAUTHORIZED );
			return;
		}

		// Invoke the next filter in the chain
		chain.doFilter( request, response );
	}
}
